<template>

  <div style="padding:10px">
    <!--    功能区域-->
    <div style="margin: 10px 0;">
      <el-button type="primary" @click="add()">新增</el-button>
    </div>
    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" style="width: 20%" placeholder="输入昵称" clearable/>
      <el-button type="primary" style="margin-left: 5px" @click="getlist">查询</el-button>
    </div>
    <el-table :data="tableData" border stripe size="large" style="width: 1400px" >
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="password" label="密码" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="age" label="年龄"  />
      <el-table-column prop="sex" label="性别" />
      <el-table-column prop="address" label="地址"/>
      <el-table-column prop="phone" label="电话号码"/>
      <el-table-column label="图片信息" min-width="120">
        <template #default="scope">
          <div class="demo-image__preview">
            <el-image
                style="width: 100px; height: 100px;"
                :preview-teleported="true"
                :src="scope.row.msg"
                :preview-src-list="[scope.row.msg]"
                :initial-index="4"
                :hide-on-click-modal="true"
                fit="contain"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button size="small"  @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定要删除吗?" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
          :current-page="currentPage"
          :page-sizes="[5,10,20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog
      title="提示"
      v-model="dialogVisible"
      width="500"
  >
    <el-form
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        label-width="120px"
        :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" style="width: 80%" autocomplete="off" />
      </el-form-item>

      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.password" type="password" style="width: 80%" autocomplete="off" show-password/>
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="ruleForm.nickname" style="width: 80%" autocomplete="off" />
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input v-model="ruleForm.age" style="width: 80%" type="number" autocomplete="off" />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio label="Male">男</el-radio>
          <el-radio label="Female">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input v-model="ruleForm.address" autocomplete="off" style="width: 80%" />
      </el-form-item>
      <el-form-item label="电话号码" prop="phone" >
        <el-input v-model="ruleForm.phone" autocomplete="off" style="width: 80%" />
      </el-form-item>
<!--      <el-form-item label="头像">-->
<!--        <el-image style="width: 100px; height: 100px"-->
<!--                  :src="ruleForm.msg"-->
<!--                  :preview-src-list="[ruleForm.msg]"-->
<!--                  :hide-on-click-modal="true"-->
<!--                  fit="cover"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="更换头像" >
        <el-upload ref="upload" action="http://localhost:8090/files/upload" :on-success="UploadSuccess">
          <el-button type="primary">上传图片</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save() ">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script setup>
import {FileDelete,AddUser, UserDelete, UserEdit} from '@/api/api'
import {getCurrentInstance, onMounted, ref} from 'vue'
import config from '@/config/config'
import { ElMessage } from 'element-plus';
import request from "../utils/request";
const url=config.baseurl+"/files/";
const search=ref('')
const currentPage=ref(1)
const pageSize=ref(10)
const flags=ref([])
const total=ref(10)
const instance = getCurrentInstance();
const dialogVisible=ref(false)
const tableData=ref(null)
const ruleForm =ref({
  id:'',
  username: '',
  password: '',
  nickname: '',
  age: null,
  sex: '',
  address: '',
  msg:'',
  phone:'',
})
const rules = ref({
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入电话号码'));
        } else {
          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
          if (!reg.test(value)) {
            callback(new Error('请输入正确的电话号码'));
          } else {
            callback();
          }
        }}, trigger: 'change'}
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
})

const UploadSuccess=(res)=>{
  if(!!ruleForm.value.msg) {
    flags.value.push(ruleForm.value.msg.replace(url, ""));
  }
  ruleForm.value.msg=res.data;
  console.log(res.data);
}
const handleEdit=(row)=>{
  flags.value=[];
  console.log("row",row);
  ruleForm.value=JSON.parse(JSON.stringify(row))
  console.log("ruleForm",ruleForm.value)
  dialogVisible.value=true;
  if(instance.refs.upload){
    instance.refs.upload.clearFiles();
  }
}
const getlist= async ()=>{
  const res =await request.get('/users/list',{params:{
      pageNum: currentPage.value,
      pageSize:pageSize.value,
      search: search.value
    }})
  console.log(res);
  tableData.value=res.data.records;
  total.value=res.data.total;
}
onMounted (async ()=>{await getlist()});

const add=()=>{
  ruleForm.value={};
  dialogVisible.value=true;
  if(instance.refs.upload){
    instance.refs.upload.clearFiles();
  }
}
const save = async () => {
  if(instance.refs.upload){
    instance.refs.upload.clearFiles();
  }
  if(!ruleForm.value.phone||!ruleForm.value.username){
    ElMessage.error('请填写完整信息');
    return;
  }
  else{
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
    if (!reg.test(ruleForm.value.phone)) {
      ElMessage.error('请输入正确的电话号码');
      return;
    }
  }
  if (ruleForm.value.id) {
    console.log("id:",ruleForm.value.id);
    const res = await UserEdit(ruleForm.value);
    console.log(res);
    if (res.data.code === 0) {
      ElMessage.success('更新成功');
    } else {
      ElMessage.error(res.data.msg);
    }
  } else {
    const res = await AddUser(ruleForm.value);
    if (res.data.code === 0) {
      ElMessage.success('保存成功');
    } else {
      console.log(res);
      ElMessage.error(res.data.msg);
    }
  }
  const FileDeletePromises =flags.value.map((item)=>{
    return FileDelete(item);
  })
  await Promise.all(FileDeletePromises);
  dialogVisible.value = false;
  ruleForm.value={};
  flags.value=[];
  await getlist();
};
const handleCurrentChange = async (page) => {
  currentPage.value=page;
  await getlist();
};
const handleSizeChange = async(size) => {
  pageSize.value=size;
  await getlist();
};
const handleDelete = async (row) => {
  const res =await UserDelete(row.id);
  if (res.data.code === 0) {
    ElMessage.success('删除成功');
  } else {
    ElMessage.error(res.data.msg);
  }
  await FileDelete(row.msg.replace(url, ''));
  await getlist();
};
</script>

<style scoped>
/* 
.el-button,
.el-input,
.el-table,
.el-dialog,
.el-form-item {
  font-size: 24px; 
}
  */

.demo-image__preview{
  height:100px;
}
</style>
